<template>
	<section>

		<el-col :span="24" class="toolbar"  style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-button type="primary" v-if="$store.state.role!='manager'" @click="handleAdd">添加教案</el-button>
				</el-form-item>				
				<el-form-item>
					<el-input v-model="key"  placeholder="输入查询的关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getList" >查询</el-button>
				</el-form-item>
			</el-form>
		</el-col>			
		<!--列表-->

		<el-tabs v-model="tabletype"  type="card">
		    <el-tab-pane label="我的教案" name='0'></el-tab-pane>
		    <el-tab-pane label="共享教案" name='1'></el-tab-pane>
		    <el-tab-pane label="内置教案" name='2'></el-tab-pane>
		</el-tabs>		
		<!--工具条-->		
		<el-table :data="Lists" highlight-current-row v-loading="loading" style="width: 100%;" @sort-change="sortChange">
			<el-table-column  type="index" width='80'>
			</el-table-column>
			<el-table-column prop="name" label="教案名称"  width="200">
			</el-table-column>
			<el-table-column prop="courseStage" label="教案类型"  width="200">
				<template scope="scope">
					<p>{{scope.row.courseStage=='0'?'创业基础教案':'案例分析教案'}}</p>
				</template>				
			</el-table-column>
			<el-table-column prop="businessModelName" label="商业模式板块"  width="200">
			</el-table-column>	
			<el-table-column prop="type" label="教案形式"  width="200">
				<template scope="scope">
					<p>{{scope.row.type=='1'?'在线文本':'上传文档'}}</p>
				</template>					
			</el-table-column>				
			<el-table-column prop="realName" label="创建人" width="200" >
			</el-table-column>
			<el-table-column prop="orgName" label="所属单位" width="200">
			</el-table-column>			
			<el-table-column prop="createTime" label="上传时间" width="200">
			</el-table-column>
			<el-table-column prop="referenceCount" label="引用次数" width="200">
			</el-table-column>			
			<el-table-column prop="birth" min-width="300" label="操作" fixed="right" >
				<template scope="scope">
					<el-button size="small" v-if="tabletype=='0'||$store.state.role=='admin'"  type="danger" @click="handleDel(scope.row)">删除</el-button>
					<el-button size="small" v-if="tabletype=='0'&&$store.state.role!='manager'||$store.state.role=='admin'" type="primary" @click="getone(scope.row,'edit')">编辑</el-button>
					<el-button size="small" type="success" @click="getone(scope.row,'look')">查看</el-button>
					<el-button size="small" type="warning" v-if="!scope.row.isShared&&tabletype!=2&&$store.state.role!='admin'&&$store.state.role!='manager'" @click="goShared(scope.row,1)">共享</el-button>
					<el-button size="small" type="info" v-if="scope.row.isShared&&tabletype=='0'&&$store.state.role!='admin'" @click="goShared(scope.row,0)">取消共享</el-button>
				</template>					
			</el-table-column>
		</el-table>
		<!--工具-->
		<el-col :span="24" class="toolbar">
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
			</el-pagination>
		</el-col>		
		<!--新增界面-->
		<el-dialog  title="新增教案" :fullscreen="false" custom-class="plandialog" width="30%"  v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addplan" status-icon class="demo-ruleForm" :rules="addplanrule" ref="addplan" label-width="50px">		
				<el-form-item label="教案类型"   prop="courseStage" label-width="80px">
				    <el-radio-group v-model="addplan.courseStage">
				      <el-radio label="0">创业基础教案</el-radio>
				      <el-radio label="1">案例分析教案</el-radio>
				    </el-radio-group>
				</el-form-item>	
			    <el-form-item label="教案名称"  prop="name" label-width="80px">
			    	<el-input style="width:50%;" placeholder="教案名称（15字以内）" type='text' v-model="addplan.name"></el-input>
			    </el-form-item>					
				<el-form-item label="所属商业模式版块" v-if="addplan.courseStage==0" label-width="150px"  prop="businessModelId" >
				    <el-select placeholder="请选择版块" v-model="addplan.businessModelId">
				      <el-option v-for="el in bussinessList" :value="el.businessModelId" :label="el.name"></el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="教案形式"  prop="type"  label-width="80px">
				    <el-radio-group v-model="addplan.type">
				      <el-radio label="1">在线文本</el-radio>
				      <el-radio label="2">上传文档</el-radio>
				    </el-radio-group>
				</el-form-item>	
			
			    <el-form-item label="上传文档"label-width="80px" v-if='addplan.type==2'>
					<el-upload
					  class="upload-demo"
					  drag
					  action="planupload"
					  :before-upload="beforeupload"
					  :file-list="fileList"
					  limit='1'
					  accept="pdf/*">
					  <i class="el-icon-upload"></i>
					  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					  <div class="el-upload__tip" slot="tip">只能上传PDF文件</div>
					</el-upload>
			    </el-form-item>				
				<el-form-item label="教案正文" prop="score" label-width="80px"  v-if='addplan.type==1'>
			        <div class="edit_container">
			          <quill-editor v-model="addplan.content"
			                        ref="myQuillEditor"
			                        class="editer"
			                       >
			          </quill-editor>
			        </div>
				</el-form-item>				
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>	
		<!--编辑界面-->
		<el-dialog  title="编辑教案" :fullscreen="false" custom-class="plandialog" width="30%"  v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editplan" status-icon class="demo-ruleForm" :rules="editplanrule" ref="editplan" label-width="50px">		
				<el-form-item label="教案类型"  prop="courseStage" label-width="80px">
				    <el-radio-group v-model="editplan.courseStage" disabled>
				      <el-radio label="0">创业基础教案</el-radio>
				      <el-radio label="1">案例分析教案</el-radio>
				    </el-radio-group>
				</el-form-item>	
			    <el-form-item label="教案名称"  prop="name" label-width="80px">
			    	<el-input style="width:50%;" type='text' placeholder="教案名称（15字以内）" v-model="editplan.name"></el-input>
			    </el-form-item>					
				<el-form-item label="所属商业模式版块" v-if="editplan.courseStage==0" label-width="150px"  prop="businessModelId" >
				    <el-select placeholder="请选择版块" v-model="editplan.businessModelId">
				      <el-option v-for="el in bussinessList" :value="el.businessModelId" :label="el.name"></el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="教案形式"  prop="type"  label-width="80px">
				    <el-radio-group v-model="editplan.type" disabled>
				      <el-radio label="1">在线文本</el-radio>
				      <el-radio label="2">上传文档</el-radio>
				    </el-radio-group>
				</el-form-item>	
			
			    <el-form-item label="上传文档"label-width="80px" v-if='editplan.type==2'>
					<el-upload
					  class="upload-demo"
					  drag
					  action="planupload"
					  :before-upload="editbeforeupload"
					  :file-list="editfileList"
					  limit='1'
					  accept="pdf/*">
					  <i class="el-icon-upload"></i>
					  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					  <div class="el-upload__tip" slot="tip">只能上传PDF文件</div>
					</el-upload>
			    </el-form-item>				
				<el-form-item label="教案正文" prop="score" label-width="80px"  v-if='editplan.type==1'>
			        <div class="edit_container">
			          <quill-editor v-model="editplan.content"
			                        ref="myQuillEditor"
			                        class="editer"
			                       >
			          </quill-editor>
			        </div>
				</el-form-item>				
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>	
		<!--查看界面-->
		<el-dialog  title="查看教案" :fullscreen="false" custom-class="plandialog" width="30%"  v-model="lookVisible" :close-on-click-modal="false">
			<el-form :model="editplan" status-icon class="demo-ruleForm" ref="editplan" label-width="50px">		
				<el-form-item label="教案类型"  prop="type" label-width="80px">
				    <el-radio-group v-model="editplan.courseStage" disabled>
				      <el-radio label="0">创业基础教案</el-radio>
				      <el-radio label="1">案例分析教案</el-radio>
				    </el-radio-group>
				</el-form-item>	
			    <el-form-item label="教案名称"  prop="name" label-width="80px">
			    	<el-input style="width:50%;"  type='text' v-model="editplan.name" disabled></el-input>
			    </el-form-item>					
				<el-form-item label="所属商业模式版块" v-if="editplan.courseStage==0" label-width="150px"  prop="businessModelId" >
				    <el-select placeholder="请选择版块" v-model="editplan.businessModelId" disabled>
				      <el-option v-for="el in bussinessList" :value="el.businessModelId" :label="el.name"></el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="教案形式"  prop="type"  label-width="80px">
				    <el-radio-group v-model="editplan.type" disabled>
				      <el-radio label="1">在线文本</el-radio>
				      <el-radio label="2">上传文档</el-radio>
				    </el-radio-group>
				</el-form-item>	
			
			    <el-form-item label="上传文档"label-width="80px" v-if='editplan.type==2'>
<!-- 					<vueshowpdf  @closepdf="closepdf" @pdferr="pdferr"  :pdfurl="editplan.path" v-show="isshowpdf"  :maxscale='4' :minscale='0.6' :scale='1.1' ></vueshowpdf>
-->	
					<iframe :src="editplan.path" width="100%" height="600px">
					 This browser does not support PDFs. Please download the PDF to view it: <a href="/test.pdf" rel="external nofollow" >Download PDF</a>
					</iframe>
			    </el-form-item>				
				<el-form-item label="教案正文" prop="score" label-width="80px"  v-if='editplan.type==1'>
			        <div class="edit_container">
			          <quill-editor v-model="editplan.content"
			                        ref="myQuillEditor"
			                        class="editer"
			                        disabled
			                       >
			          </quill-editor>
			        </div>
				</el-form-item>				
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="lookVisible = false">关闭</el-button>
			</div>
		</el-dialog>			
	</section>
</template>
<script>
	import { planlist,plandelete,planadd,planone,planedit,bussinesslist,planlistbuil,plannamerule} from '../../api/api';
	import { quillEditor } from 'vue-quill-editor' //调用编辑器
	import vueshowpdf from 'vueshowpdf'
	//import NProgress from 'nprogress'
	export default {
		data() {
			var rulesname=(rules,value,callback)=>{
				let params={name:this.addplan.name};
				plannamerule(params).then((r)=>{
					if(!r){
						callback(new Error('教案名称重复'))
					}else{
						callback()
					}
				})
			}	
			var editrulesname=(rules,value,callback)=>{
				if(this.editplan.checkname!=this.editplan.name){			
					let params={name:this.editplan.name};
					plannamerule(params).then((r)=>{
						if(!r){
							callback(new Error('教案名称重复'))
						}else{
							callback()
						}
					})
				}else{
					callback()
				}
			}				
			let numberrule=(rule, value, callback)=>{
			  if (value < 0 || value > 10) {
			    callback(new Error('分值必须在 0 至 10之间'))
			  } else {
			    callback()
			  }							
			}
			let namelengthrule=(rule, value, callback)=>{
			  if (value.length > 15) {
			    callback(new Error('限制字数15字以内'))
			  } else {
			    callback()
			  }							
			}				
			return {
				Type:"",
				addFormVisible: false,
				addLoading: false,	
				autoplan:false,
				isshowpdf:true,
				editFormVisible: false,
				editLoading: false,						
				loading: true,
				lookVisible:false,
				planupload:"plan",
				Lists:[],
				fileList:[],
				editfileList:[],	
				bussinessList:[],
				addplan:{
					name:"",
					type:"",
					content:"",
					path:"",
					courseStage:"",
					businessModelId:"",
					src:"",
				},
				editplan:{

				},					
				addplanrule: {
					name: [
						{ required: true, message: '请填写教案名称', trigger: 'blur' },
						{validator:rulesname,trigger: 'blur'},
						{validator:namelengthrule,trigger: 'blur'}
					],
					courseStage:[
						{ required: true, message: '请选择教案类型', trigger: 'blur' }
					],					
					type:[
						{ required: true, message: '请选择教案形式', trigger: 'blur' }
					],
					score:[
						{required: true, validator:numberrule, trigger: 'blur'}
					],
					businessModelId:[
						{ required: true, message: '请选择所属商业模式版块', trigger: 'blur' }
					],
					content:[
						{ required: true, message: '请填写教案内容', trigger: 'blur' }
					]				
				},	
				editplanrule: {
					name: [
						{ required: true, message: '请填写教案名称', trigger: 'blur' },
						{validator:editrulesname,trigger: 'blur'},
						{validator:namelengthrule,trigger: 'blur'}
					],
					courseStage:[
						{ required: true, message: '请选择教案类型', trigger: 'blur' }
					],					
					type:[
						{ required: true, message: '请选择教案形式', trigger: 'blur' }
					],
					score:[
						{required: true, validator:numberrule, trigger: 'blur'}
					],
					businessModelId:[
						{ required: true, message: '请选择所属商业模式版块', trigger: 'blur' }
					]	
				},				
				editoptionBox:[],
				param:"",
				editparam:"",	
				page:"1",
				pagesize:"10",
				total:'',
				key:"",
				tabletype:'0',
				isShared:"",
				isSelf:"1",
				sign:'1',
			}
		},
	    computed: {
	      editor() {
	        return this.$refs.myQuillEditor.quill
	      }
	    },			
	    components: {
		  vueshowpdf,
	      quillEditor
	    },    		
		watch:{
			'tabletype':function(){
				this.pageNum='1';
				if(this.tabletype==0){
					this.isShared='';
					this.sign=1;
				}
				if(this.tabletype==1){
					this.isShared=1;
					this.sign=2;
				}	
				if(this.tabletype==2){
					this.isShared='';
					this.sign=3
				}				
				this.getList();
			},
			'checkbox':function(){
				console.log(this.checkbox)
			}
		},
		methods: {	
		    sortChange:function(column, prop, order){
				if(column){
			      var type='';
			      if(column.prop=='createTime'){
			      	column.prop='create_time';
			      }else if(column.prop=='referenceCount'){
			      	column.prop='reference_count';
			      }
			      if(column.order=="ascending"){
			      	type=column.prop;	
			      }else if(column.order=='descending'){
			      	type=column.prop+' '+'desc';
			      }
			      this.getList(type)			 	
				}
		    },			
			closepdf:function(){
				this.isshowpdf=false;
			},
	       pdferr(errurl) {
	            console.log(errurl);
	        },		
            beforeupload(file) {
                //创建临时的路径来展示图片
                var windowURL = window.URL || window.webkitURL;
                this.addplan.src=windowURL.createObjectURL(file);
                var planname=file.name;
                let oneplan={name:planname,url:this.addplan.src};
                this.fileList=[];
                this.fileList.push(oneplan);
                //重新写一个表单上传的方法
                this.param = new FormData();
                this.param.append('file', file, file.name);
                return false;
            },	
            editbeforeupload(file) {
                //创建临时的路径来展示图片
                var planname=file.name;
                var windowURL = window.URL || window.webkitURL;
                this.editplan.src=windowURL.createObjectURL(file);
                let oneplan={name:planname,url:this.addplan.src};
                this.editfileList=[];
                this.editfileList.push(oneplan);
                //重新写一个表单上传的方法
                this.editparam = new FormData();
                this.editparam.append('file', file, file.name);
                return false;
            },	
			goShared:function(row,type){
				this.$confirm('确定操作吗?', '提示', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',					
					type: 'warning'
				}).then(() => {
					var params=new URLSearchParams();
					params.append('isShared',type);
					params.append('planId',row.planId);
					planedit(params).then((r) => {
						if(!r.error){
							this.$message({
								message: '操作成功',
								type: 'success'
							});
							this.getList();									
						}else{
							this.$message({
								message: '操作失败',
								type: 'error'
							});						
						}
					})	
				})				
			
			},
			handleAdd: function () {
				this.addFormVisible = true;
			},
			//获取商业模式列表
			getbussinesslist:function(){
				bussinesslist().then((res)=>{
					$.each(res, function(i,value) {
						value.businessModelId=JSON.stringify(value.businessModelId)
					});
					this.bussinessList=res;
				})
			},	
			//获取项目列表
			getList: function (type) {
				this.loading = true;
				//NProgress.start();
				let params={pageNum:this.page,pageSize:this.pagesize,key:this.key,isShared:this.isShared,sign:this.sign,orderByClause:type};
				planlist(params).then((res) => {
					this.total=res.total;					
					this.Lists = res.list;
					this.loading = false;
					//NProgress.done();
				});	
			},
			getone:function(row,type){
				var params=row.planId;
				this.editoptionBox=[];
				planone(params).then((res)=>{			
					if(!res.error){
						if(type=='edit'){
							this.editFormVisible=true;
						}else{
							this.lookVisible=true;
						}
						res.src='';
						res.type=JSON.stringify(res.type);				
						res.courseStage=JSON.stringify(res.courseStage);
						res.checkname=res.name;
						res.businessModelId=JSON.stringify(res.businessModelId);
						var info={name:res.name,url:res.path};
						this.editfileList=[];
						this.editfileList.push(info);						
						this.editplan = Object.assign({}, res);
					}
				})
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getList();
			},		            
			handleDel:function (row) {
				this.$confirm('确认删除该记录吗?', '提示', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',					
					type: 'warning'	
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para =row.planId;				
					plandelete(para).then((res) => {
						if(!res.error){
							this.listLoading = false;
							//NProgress.done();
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.getList();							
						}
					});
				})
			},
			//新增
			addSubmit: function () {					
				if(this.addplan.type==2){
					var _this= this;
					_this.addplan.content="";
					if(_this.addplan.src==''){
				        _this.$message({
				          showClose: true,
				          message: '请选择上传文件',
				          type: 'error'
				        });					
				        return;
					}					
				}
				if(this.addplan.type==1){
					this.param=new URLSearchParams()
				}			
				this.$refs.addplan.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {
					        confirmButtonText: '确定',
					        cancelButtonText: '取消',					
							type: 'warning'								
						}).then(() => {
							this.addLoading = true;
							this.param.append('name',this.addplan.name);
							this.param.append('type',this.addplan.type);
							this.param.append('content',this.addplan.content);
							this.param.append('courseStage',this.addplan.courseStage);
							if(this.addplan.courseStage==0){
								this.param.append('businessModelId',this.addplan.businessModelId);
							}								
							planadd(this.param).then((r) => {
								if(!r.error){
									this.addLoading = false;
									this.$message({
										message: '添加成功',
										type: 'success'
									});
									this.addplan={
										name:"",
										type:"",
										content:"",
										path:"",
										courseStage:"",
										businessModelId:"",
										src:"",
									};
									this.fileList=[];
									this.addFormVisible = false;
									this.param='';
									this.getList();									
								}else{
									this.addLoading = false;
									this.param='';
									this.$message({
										message: '添加失败',
										type: 'error'
									});										
								}
							}).catch(() => {
								this.addLoading = false;					
							});	
						});
					}
				});
			},
			//编辑
			editSubmit: function () {
				if(this.editplan.type==2){
					var _this= this;
					_this.editplan.content="";
					if(_this.editplan.src==''){
						this.editparam=new URLSearchParams();
						this.editparam.append('path',this.editplan.path);
					}					
				}
				if(this.editplan.type==1){
					this.editparam=new URLSearchParams()
				}		
				this.$refs.editplan.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {
					        confirmButtonText: '确定',
					        cancelButtonText: '取消',					
							type: 'warning'								
						}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							this.editparam.append('name',this.editplan.name);
							this.editparam.append('type',this.editplan.type);
							this.editparam.append('content',this.editplan.content);
							this.editparam.append('planId',this.editplan.planId);
							this.editparam.append('courseStage',this.editplan.courseStage);
							if(this.editplan.courseStage==0){
								this.editparam.append('businessModelId',this.editplan.businessModelId);
							}							
							planedit(this.editparam).then((r) => {
								if(!r.error){
									this.editLoading = false;
									this.$message({
										message: '更新成功',
										type: 'success'
									});
									this.$refs['editplan'].resetFields();
									this.editFormVisible = false;
									this.editparam='',
									this.getList();									
								}else{
								    this.editLoading = false;
									this.editparam='',
									this.$message({
										message: '更新失败',
										type: 'error'
									});											
								}
							}).catch(() => {
								this.editLoading = false;					
							});	
						});
					}
				});
			},			
		},
		mounted() {
			this.getList();
			this.getbussinesslist()
		}
	};

</script>

<style>

.planauto{
	display: none;
}
</style>